package presentation.models;

import java.awt.Color;
import java.awt.Component;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JOptionPane;

import presentation.UIPost;
import util.NotFoundException;
import domain.ForumLogic;

/**
 * cell renderer for the post list in the thread
 * (sets the way each element in the list is presented)
 */
public class PostListCellRenderer extends DefaultListCellRenderer
{

	private static final long serialVersionUID = 5981814325757287371L ;

	private static Color _ALT_ROW = new Color(255, 153, 255);

	private ForumLogic forum;


	/**
	 * Constructor
	 * @param forum - in order to get the usernames of the writers for presentation
	 */
	public PostListCellRenderer(final ForumLogic forum)
	{
		this.forum = forum;

	}


	/**
	 * get the cell renderer of the post list for a certain element
	 */
	/* (non-Javadoc)
	 * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
	 */
	@Override
	public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected,
		final boolean cellHasFocus)
	{
		super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

		// formating the post for presentation in the list
		UIPost post = (UIPost) value;
		SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy  kk:mm");
		String timeOfPost = df.format(post.getDate());
		try
		{
			String username = (this.forum.getMemberById(post.getWriterId())).getUsername();
			this.setText("Author: "+ username + " ,  Created: " + timeOfPost);
		}
		catch(NotFoundException e)
		{
			JOptionPane.showMessageDialog(PostListCellRenderer.this,
				"Can't find user, sorry...", "error occured", JOptionPane.ERROR_MESSAGE);
		}
		catch(RemoteException e)
		{
			JOptionPane.showMessageDialog(PostListCellRenderer.this,
				"Remote exception, sorry...", "error occured", JOptionPane.ERROR_MESSAGE);
		}

		if (!isSelected && index % 2 == 0)
		{
			this.setBackground(PostListCellRenderer._ALT_ROW);
		}
		return this;
	}

}

